<template>
  <ex-dialog width="50%" class="ex-diolog" :title="title" :visible="visible" :close-on-click-modal="false"
    @closeDialog="handleClose">
    <div class="main" v-loading="loading">
      <el-tabs v-model="activeName">
        <el-tab-pane label="基本设置" name="first">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" :label-width="labelWidth" class="demo-ruleForm">
            <el-form-item label="商品类型：" prop="type" :key="1">
              <el-select v-model="ruleForm.type" placeholder="请选择商品类型" filterable :disabled="disabled"
                :style="{width: inputWidth}" @change="typeChange">
                <el-option v-for="(item,index) in commodityType" :key="index" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <!-- 实物商品/盲盒券 -->
            <div v-if="ruleForm.type==1||ruleForm.type==5">
              <el-form-item label="商品名称：" prop="name" ref="refOne" :key="2">
                <el-input v-model="ruleForm.name" placeholder="请输入商品名称" :style="{width: inputWidth}"></el-input>
              </el-form-item>
              <el-form-item label="商品图片：" prop="img" ref="imgRef" :key="3">
                <ImageUploadMore :limit="1" :fileSize="20" @successImg="getImg" :value="ruleForm.img">
                </ImageUploadMore>
              </el-form-item>
            </div>
            <!-- NFR -->
            <div v-if="ruleForm.type==2">
              <el-form-item label="数字权益卡：" prop="businessId" ref="refOne" :key="4">
                <el-select v-model="ruleForm.businessId" placeholder="请选择数字权益卡" filterable :disabled="disabled"
                  :style="{width: inputWidth}">
                  <el-option v-for="(item,index) in cardOptins" :key="index" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </div>
            <!-- 线上权益 -->
            <div v-if="ruleForm.type==3">
              <el-form-item label="线上权益：" prop="businessId" ref="refOne" :key="5">
                <el-select v-model="ruleForm.businessId" placeholder="请选择线上权益" :disabled="disabled" filterable
                  :style="{width: inputWidth}">
                  <el-option v-for="item in equityOptins" :key="item.id" :label="item.value" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="商品图片：" prop="img" ref="imgRef" :key="6">
                <ImageUploadMore :limit="1" :fileSize="20" @successImg="getImg" :value="ruleForm.img">
                </ImageUploadMore>
              </el-form-item>
            </div>
            <el-form-item label="商品库存：" prop="stock" :key="7">
              <el-input v-model.number="ruleForm.stock" placeholder="请输入商品库存" :style="{width: inputWidth}"
                :disabled="disabled"></el-input>
            </el-form-item>
            <el-form-item label="虚拟库存：" prop="virtualStock" :key="8">
              <el-input v-model.number="ruleForm.virtualStock" placeholder="请输入虚拟库存" :style="{width: inputWidth}">
              </el-input>
            </el-form-item>
            <el-form-item label="赠券数量：" prop="couponNum" v-if="ruleForm.type==5" :key="9">
              <el-input v-model.number="ruleForm.couponNum" placeholder="请输入赠券数量" :style="{width: inputWidth}">
              </el-input>
            </el-form-item>
            <!-- <el-form-item label="商品价格：" prop="priceType" :key="10">
              <el-select v-model="ruleForm.priceType" placeholder="请选择" filterable :style="{width: inputWidth}"
                @change="changePriceType">
                <el-option v-for="item in options" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="price" :key="11">
              <el-input v-model="ruleForm.price" :placeholder="priceText" :style="{width: inputWidth}"></el-input>
            </el-form-item>
            <el-form-item label="商品手续费：" prop="feeType" :key="12">
              <el-select v-model="ruleForm.feeType" placeholder="请选择" filterable :style="{width: inputWidth}"
                @change="changeFeeType">
                <el-option v-for="item in options" :key="item.id" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item> 
            <el-form-item label="" prop="fee" :key="13">
              <el-input v-model="ruleForm.fee" :placeholder="feeText" :style="{width: inputWidth}"></el-input>
            </el-form-item> -->
            
            <el-form-item label="支付类型：" prop="payType" :key="10">
              <el-select v-model="ruleForm.payType" placeholder="请选择" filterable :style="{width: inputWidth}"
                @change="changePriceType">
                <el-option v-for="(item,index) in payTypeList" :key="index" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="现金支付：" prop="cash" :key="11" v-if="ruleForm.payType == 2 || ruleForm.payType == 3">
              <el-input v-model="ruleForm.cash" placeholder="请输入现金支付金额" :style="{width: inputWidth}"></el-input>
            </el-form-item>
            <el-form-item label="积分支付：" prop="priceType" :key="12" v-if="ruleForm.payType == 1 || ruleForm.payType == 3">
              <el-select v-model="ruleForm.priceType" placeholder="请选择" filterable :style="{width: inputWidth}"
                @change="changePriceType">
                <el-option v-for="(item,index) in options" :key="index" :label="item.value" :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="" prop="price" :key="13" v-if="ruleForm.payType == 1 || ruleForm.payType == 3">
              <el-input v-model="ruleForm.price" placeholder="请输入积分支付金额" :style="{width: inputWidth}"></el-input>
            </el-form-item>

            <el-form-item label="限制兑换：" prop="" required :key="14">
              <el-radio-group v-model="ruleForm.exchangeLimitType">
                <div style="margin: 10px 0 15px">
                  <el-radio :label="'1'">不限购</el-radio>
                </div>
                <div style="display: flex;align-items:center">
                  <el-radio :label="'2'">限购数量</el-radio>
                  <el-form-item prop="exchangeLimitNum" v-if="ruleForm.exchangeLimitType==2" :key="15">
                    <el-input placeholder="请输入" v-model.number="ruleForm.exchangeLimitNum" style="width: 190px">
                      <template slot="append">件</template>
                    </el-input>
                  </el-form-item>
                </div>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="排序：" prop="sort" :key="16">
              <el-input v-model.number="ruleForm.sort" placeholder="请输入" :style="{width: inputWidth}">
              </el-input>

            </el-form-item>
            <el-form-item label="使用规则：" prop="rule" :key="17">
              <el-input v-model="ruleForm.rule" type="textarea" :autosize="{ minRows: 4, maxRows: 10}"
                placeholder="请输入使用规则" :style="{width: inputWidth}"></el-input>
            </el-form-item>
            <el-form-item label="是否上架：" prop="status" required :key="18">
              <el-switch v-model="ruleForm.status" :active-value="'1'" :inactive-value="'2'" active-text="是"
                inactive-text="否">
              </el-switch>
            </el-form-item>
            <!-- <el-form-item label="图片状态：" prop="status" :label-width="labelWidth">
          <el-switch v-model="ruleForm.status" active-text="启用" inactive-text="禁用" active-value="1" inactive-value="2">
          </el-switch>
        </el-form-item> -->
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="图文详情" name="second">
          <!-- <editor v-model="ruleForm.content" :min-height="200" placeholder="请输入通知公告正文" /> -->
          <div class="richText">
            <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="ruleForm.content" :defaultConfig="editorConfig"
              :mode="mode" @onCreated="onCreated" @onChange="onChange" />
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    <div class="button_box">
      <el-button type="primary" :loading="AgreeLoading" @click="submitForm('ruleForm')" v-if="id==null">立即创建</el-button>
      <el-button type="primary" :loading="AgreeLoading" @click="editForm('ruleForm')" v-if="id!=null">保存</el-button>
      <el-button @click="handleClose">取消</el-button>
    </div>
  </ex-dialog>
</template>
<script>
  import Loading from "@/components/Loading/index";
  // import Editor from '@/components/Editor';
  import '@wangeditor/editor/dist/css/style.css'
  import {
    Editor,
    Toolbar
  } from "@wangeditor/editor-for-vue";
  // api
  import {
    addIntegralCommodity,
    getCardOptins,
    getEquityOptins,
    integralGetInfo,
    editIntegral,
    currentInventorySelect
  } from "@/api/integralOperation";

  export default {
    components: {
      Loading,
      // Editor,
      Editor,
      Toolbar
    },
    props: {
      visible: Boolean,
      id: String,
    },
    data() {
      var validateStock = (rule, value, callback) => {
        console.log('validateEnd', rule)
        var reg = /^-?[1-9]\d*$/
        if (value === '') {
          callback(new Error('请输入商品库存'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入整数')); 
        } else {
          callback()
        }
      };
      var validateVirtualStock = (rule, value, callback) => {
        var reg = /^[1-9]\d*|0$/
        if (value === '') {
          callback(new Error('请输入虚拟库存数量'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入大于等于0的整数')); 
        } else {
          callback()
        }
      }; 
      var validateCashk = (rule, value, callback) => {
        var reg = /(^[0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
        if (value === '') {
          callback(new Error('请输入现金支付金额'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入大于等于0的数值，可保留两位小数')); 
        } else {
          callback()
        }
      };
      var validatePrice = (rule, value, callback) => {
        var reg = /(^[0-9](\d+)?(\.\d{1,2})?$)|(^\d\.\d{1,2}$)/
        if (value === '') {
          callback(new Error('请输入积分支付金额'));
        } else if (!reg.test(value)) {
          callback(new Error('请输入大于等于0的数值，可保留两位小数')); 
        } else {
          callback()
        }
      };
      // 
      return {
        labelWidth: '120px',
        inputWidth: '300px',
        title: '新增',
        loading: false,
        activeName: 'first',
        disabled: false,
        action: process.env.VUE_APP_BASE_API + "/common/v1/upload",
        info: {},
        AgreeLoading: false, //按钮loading
        options: [],
        payTypeList: [],//支付类型
        commodityType: [], //商品类型下拉数组
        cardOptins: [], //权益卡数组
        equityOptions: [], //权益数组
        labelWidth: '120px',
        ruleForm: {
          // 
          businessId: '', //业务id 数字权益卡id等
          content: '', //图文详情
          price: '', //积分支付金额
          priceType: '', //积分支付类型 1神椰coco 2 椰分
          id: '', //
          img: '', //商品图片
          name: '', //商品名称
          price: '', //商品价格
          priceType: '', //价格类型1神椰coco 2 椰分
          rule: '', //使用规则
          status: '', //状态 1 上架 2 下架 3 停用
          stock: '', //库存数量
          type: '', //商品类型 1实物 2NTR 3线上权益
          virtualStock: '', //虚拟库存数量
          exchangeLimitType: '1', //限制兑换类型 1 不限购 2 限购数量
          exchangeLimitNum: '', //限购数量
          sort: '', //排序
          couponNum:'',//赠券数量 
          payType: '', //支付类型
          cash: '', //现金支付
        },
        feeText: '请输入商品手续费',
        priceText: '请输入商品价格',
        rules: {
          type: [{
            required: true,
            message: '请选择商品类型',
            trigger: 'change'
          }],
          name: [{
            required: true,
            message: "请输入商品名称",
            trigger: ['change', 'bulr'],
          }],
          img: [{
            required: true,
            message: "请选择商品图片",
            trigger: ['change', 'bulr'],
          }],
          businessId: [{
            required: true,
            message: "请选择",
            trigger: 'change',
          }],
          stock: [{
            required: true,
            validator: validateStock,
            trigger: ['change', 'bulr'],
          }],
          priceType: [{
            required: true,
            message: '请选择商品价格类型',
            trigger: 'change'
          }],
          price: [{
            required: true,
            validator: validateStock,
            trigger: ['change', 'bulr'],
          }],
          feeType: [{
            required: true,
            message: '请选择商品手续费类型',
            trigger: 'change'
          }],
          price: [{
            required: true,
            validator: validatePrice,
            trigger: ['change', 'bulr'],
          }],
          rule: [{
            required: true,
            message: "请输入使用规则",
            trigger: ['change', 'bulr'],
          }],
          virtualStock: [{
            required: true,
            validator: validateVirtualStock,
            trigger: ['change', 'bulr'],
          }],
          exchangeLimitNum: [{
            required: true,
            message: "请输入限购数量",
            trigger: ['change', 'bulr'],
          }],
          sort: [{
            required: true,
            message: "请输入排序",
            trigger: ['change', 'bulr'],
          }],
          couponNum: [{
            required: true,
            message: "请输入赠券数量",
            trigger: ['change', 'bulr'],
          }],
          payType: [{
            required: true,
            message: '请选择支付类型',
            trigger: 'change'
          }],
          cash: [{
            required: true,
            validator: validateCashk,
            trigger: ['change', 'bulr'],
          }],
        },
        // 富文本配置
        logoUploadUrlImg: process.env.VUE_APP_BASE_API + "/common/v1/upload", //图片接口
        videoUploadUrl: process.env.VUE_APP_BASE_API + "/common/v1/upload", //视频接口
        editor: null,
        html: "<p>hello&nbsp;world</p>",
        toolbarConfig: {
          // toolbarKeys: [ /* 显示哪些菜单，如何排序、分组 */ ],
          // excludeKeys: [ /* 隐藏哪些菜单 */ ],
          excludeKeys: ['group-video']
        },
        editorConfig: {

          placeholder: "请输入内容...",
          // autoFocus: false,
          // 所有的菜单配置，都要在 MENU_CONF 属性下
          MENU_CONF: {},
        },
        mode: 'default', // or 'simple'
      };
    },
    computed: {},
    created() {
      this.getCardDict()
      this.getPayTypeDict()
      this.getOptions()
      this.getCardOptinsInfo()
      this.getEquityOptinsInfo()
      console.log(this.id)
      if (this.id != null) {
        this.title = '编辑'
        this.disabled = true
        this.getInfo()
      }

    },
    mounted() {
      var _this = this
      // 配置上传图片
      var name = ''
      this.editorConfig.MENU_CONF['uploadImage'] = {
        server: _this.logoUploadUrlImg,
        // headers: _this.headers,
        fieldName: 'file',
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        onSuccess(file, res) {
          name = file.name
          // console.log(`${file.name} 上传成功`, res)
        },
        customInsert(res, insertFn) {
          console.log(res)
          insertFn(res.result.url, name, res.result.url)
        }
      }
      // 配置上传视频
      this.editorConfig.MENU_CONF['uploadVideo'] = {
        server: _this.videoUploadUrl,
        // headers: _this.headers,
        fieldName: 'file',
        maxFileSize: 500 * 1024 * 1024,
        //    async customUpload(file, insertFn) {
        //        console.log(file)
        //     // file 即选中的文件
        //     // 自己实现上传，并得到图片 url alt href
        //     // 最后插入图片
        //     //   insertFn(url, alt, href)
        //     },
        customInsert(res, insertFn) {
          // res 即服务端的返回结果
          // 从 res 中找到 url ，然后插入
          insertFn(res.result.url)
        },
      }
    },
    methods: {
      //获取商品类型字典
      getCardDict() {
        var dictType = "bee_integral_commodity_type";
        this.$getSelectList(dictType)
          .then((res) => {
            this.commodityType = res.result[0].dictList;
            this.commodityType.forEach((item, index) => {
              if (item.id == '4') {
                this.commodityType.splice(index, 1)
              }
            })
          })
          .finally(() => {

          });
      },
      //获取支付类型
      getPayTypeDict() {
        var dictType = "bee_integral_commodity_pay_type";
        this.$getSelectList(dictType)
        .then((res) => {
          this.payTypeList = res.result[0].dictList;
        })
        .finally(() => {

        });
      },
      
      //获取类型 1神椰coco 2 椰分
      getOptions() {
        var dictType = "bee_integral_commodity_price_type";
        this.$getSelectList(dictType)
          .then((res) => {
            this.options = res.result[0].dictList;
          })
          .finally(() => {

          });
      },
      //获取权益库存下拉框
      getCardOptinsInfo() {
        getCardOptins().then((res) => {
            this.cardOptins = res.result
          })
          .finally(() => {});
      },
      //权益库存下拉框
      getEquityOptinsInfo() {
        let data = {
          type:''
        }
        currentInventorySelect(data).then((res) => {
            this.equityOptins = res.result
          })
          .finally(() => {});
      },
      // 获取商品图片
      getImg(e) {
        this.ruleForm.img = e
        this.$refs['imgRef'].clearValidate();
      },
      //商品类型选择
      typeChange(e) {
        this.ruleForm.businessId = ''
        // this.$refs['refOne'].clearValidate();
      },
      // 富文本操作
      onCreated(editor) {
        this.editor = Object.seal(editor); // 【注意】一定要用 Object.seal() 否则会报错
        console.log('this.editor', this.editor)
      },
      onChange(editor) {
        console.log("onChange", editor.getHtml()); // onChange 时获取编辑器最新内容
      },
      getEditorText() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getText()); // 执行 editor API
      },
      printEditorHtml() {
        const editor = this.editor;
        if (editor == null) return;

        console.log(editor.getHtml()); // 执行 editor API
      },
      //取消
      handleClose(formName) {
        this.$emit("update:visible", false);
      },
      getInfo() { //获取信息详情
        this.loading = true
        integralGetInfo(this.id).then((res) => {
            this.loading = false
            
            this.ruleForm = res.result
          })
          .finally(() => {
            this.loading = false;
          });
      },
      submitForm(formName) {
        //创建确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // if (this.ruleForm.content == '') {
            //   this.$message.error('请填写文章内容');
            //   return
            // }
            this.AgreeLoading = true
            var params = {
              ...this.ruleForm,
            };
            addIntegralCommodity(params).then((res) => {
                this.$message({
                  message: "保存成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  // setTimeout(() => {
                  //   this.AgreeLoading = false
                  // }, 2000)
                  this.AgreeLoading = false
                }, 1000);
              })
              .catch(() => {
                this.AgreeLoading = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      editForm(formName) {
        //编辑确定
        this.$refs[formName].validate((valid) => {
          if (valid) {
            //   alert("submit!");editGroupon
            this.AgreeLoading = true
            var params = {
              id: this.id,
              ...this.ruleForm,
            };
            editIntegral(params).then((res) => {
                this.$message({
                  message: "修改成功",
                  type: "success",
                });
                setTimeout(() => {
                  this.$emit('success')
                  this.handleClose()
                  this.AgreeLoading = false
                }, 1000);
              })
              .catch(() => {
                this.AgreeLoading = false;
              });

          } else {
            console.log("error submit!!");
            return false;
          }
        });
      },
      changePriceType(e) {
        console.log('e', e)
        if (e == 1) {
          this.priceText = '请输入商品价格'
        } else if (e == 2) {
          this.priceText = '请输入椰分数量'
        }
      },
      changeFeeType(e) {
        if (e == 1) {
          this.feeText = '请输入商品手续费'
        } else if (e == 2) {
          this.feeText = '请输入椰分数量'
        }
      }
    },
  };

</script>
<style lang="scss" scoped>
  .ex-diolog {
    ::v-deep .ex--dialog--footer {
      border: none !important;
      padding: 0 !important;
    }

    ::v-deep .ex--dialog--main {
      padding: 10px 20px !important;
    }
  }

  .main {
    padding: 20px 20px;
  }

  .from_box {
    display: flex;
    margin-bottom: 20px;
  }

  .from_box_l {
    width: 110px;
    color: #606266;
    font-size: 14px;
    font-weight: bold;
  }

  .from_box_r {
    color: #333;
    font-size: 15px;
    flex: 1;
  }

  .el_table_box {
    padding: 0 20px 40px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    margin-bottom: 20px;
  }

  .el_table_box_h {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #f3f3f3;
    margin-bottom: 14px;
  }

  .el_table_box_h_title {
    border-left: 4px solid #ff9300;
    padding-left: 4px;
  }

  .carousel_box {
    width: 400px;
    margin-bottom: 20px;
  }

  .swiper_img {
    width: 100%;
    height: 100%;
  }

  .carousel_box_two {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
  }

  .phone_box {
    width: 100px;
    height: 100px;
    margin: 0 10px 10px 0;
  }

  .button_box {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px 0;
  }

  ::v-deep .avatar-uploader2 .el-upload {
    width: 100% !important;
  }

  .avatar-uploader2 {
    width: 228px;
    height: 128px;
    text-align: center;
    line-height: 128px;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
  }

  .banner_img {
    width: 228px;
    height: 128px;
  }

  .richText {
    border: 1px solid #ccc;
    line-height: normal;
  }

</style>
